const processWidget = this.pageObj.getApiWidgetByAliasName('modal-process');
const queryManage = this.pageObj.getApiWidgetByAliasName('queryManage')?.widgetObj;
const formObj = this.getApiPage().getApiWidgetByAliasName('judge-content')?.widgetObj;
const prefix = this.pageObj.getVariables().find(v => v.name === "environmentType")?.value || '';
const url = new URLSearchParams(window.location.href);
let personDetail = JSON.parse(url && url.get('personDetail') || '{}');
const taskTypeEnum = { 信息发布: '1', 信息上报: '2', 下发任务: '10' };
const process = processWidget?.widgetObj;
const authToken = this.pageObj.getVariables().find(v => v.name === 'AuthToken')?.value

function basePost(url, body) {
    const option = {
        method: 'POST',
        headers: { "Content-type": "application/json" },
        body: JSON.stringify(body)
    }
    return fetch(url, option).then(res => res.json())
}

if (formObj && process) {
    const { dataSource } = formObj._option;
    const configs = process.configs();
    const Modal = process.getModal();
    const defaultData = {
        ...dataSource,
        eventId: dataSource.id,
        eventTitle: dataSource.drillName,

        taskTypeId: taskTypeEnum[$event],
        taskTypeName: $event,
        // 下发部门
        taskIssuDepart: personDetail.deptCode,
        taskIssuDepartName: personDetail.deptName,

        // 下发人
        taskIssuer: personDetail.id,
        taskIssuerName: personDetail.personName,

        // 记录人
        takenotesPersonName: personDetail.personName,
        takenotesPersonId: personDetail.id,
        // 进度
        progress: dataSource.disableFlag ?? dataSource.whetherProcess,
    };

    console.log($event, configs, defaultData);


    let config;
    const $form = this.getApiPage().getApiWidgetByAliasName('edit-form')?.widgetObj;
    const $editTitle = this.getApiPage().getApiWidgetByAliasName('edit-title')?.getElement();
    let style = {};
    const hasUpload = $form._option.config.find(item => item.dataIndex === 'thumbnailPath')
    const configUpload = [
        {
            "label": "图片上传：",
            "dataIndex": "thumbnailPath",
            "upload": {
                "uploadUrl": "/Doc/file/uploadFile",
                "bucketName": "project",
                "fileDirPath": "event",
                "storageUrl": "/Doc/file/getObjectUrl",
                "accept": "image/*",
                "number": 10,
                "isLink": true
            },
            "type": "upload"
        },
        {
            "label": "录像回放：",
            "dataIndex": "jpbPath",
            "upload": {
                "uploadUrl": "/Doc/file/uploadFile",
                "bucketName": "project",
                "fileDirPath": "event",
                "storageUrl": "/Doc/file/getObjectUrl",
                "accept": "video/*",
                "number": 10,
                "isLink": true
            },
            "type": "upload"
        }]
    switch($event) {
        case '记录动态':
            config = configs['记录动态'](2);
            break;
        case '结束演练':
            config = configs['自定义内容']('提示：是否确定结束演练');
            /*queryManage.updateDrill(data.id, { disableFlag: 1 }).then(res => {
              this.getApiPage().setVariables([{ name: 'update', value: data.id }]);
              const detail = this.getApiPage().getApiWidgetsByClassName('detail');
              detail?.forEach(v => v.hideWidget())
            });*/
            // config = configs['自定义内容']('提示：是否确定为误警事件', '确定')
            break;
        case '解除演练':
            config = configs['自定义内容']('提示：是否确定解除演练');
            /*queryManage.updateDrill(data.id, { disableFlag: 3 }).then(res => {
              this.getApiPage().setVariables([{ name: 'update', value: data.id }]);
              const detail = this.getApiPage().getApiWidgetsByClassName('detail');
              detail?.forEach(v => v.hideWidget())
            });*/
            break;
        case '进入演练':
            console.log('进入演练: => ', defaultData);
            this.getApiPage().navigateStage(
                '843057919439142912',
                [
                    { name: 'screen_params', value: JSON.stringify(defaultData) },
                    { name: 'AuthToken', value: authToken },
                    { name: 'environmentType', value: prefix }
                ]
            );
            break;
        case '匹配方案':
            basePost(`/${prefix}Event/drillPlanInfo/update`, { id: dataSource.id, disableFlag: -1 })
                .then(json => {
                    if (json) {
                        this.getApiPage().setVariables([{ name: 'update', value: defaultData.id }]);
                        // window.parent.postMessage({ type: 'nav/style', pageName: '演练' }, document.referrer);
                        this.getApiPage().navigateStage(
                            '843567423519981568',
                            [
                                { name: 'screen_params', value: JSON.stringify(defaultData) },
                                { name: 'AuthToken', value: authToken },
                                { name: 'environmentType', value: prefix }
                            ]
                        );
                    }
                })
            // config = configs['自定义内容']('提示：是否确定关闭事件', '确定')
            break;
        case '变更演练':
        case '修改演练':
            this.hideWidget()
            if (!hasUpload) $form._option.config = configUpload.concat($form._option.config);
            this.getApiPage().getApiWidgetsByClassName('detail')?.forEach(v => v.hideWidget());
            this.getApiPage().getApiWidgetsByClassName('edit')?.forEach(v => v.showWidget());
            let info;
            try {
                if(dataSource.eventDetails) info = JSON.parse(dataSource.eventDetails)
            } catch (e) {
                console.error(e)
            }

            // 演练位置
            dataSource.thumbnailPath = info?.thumbnailPath;
            dataSource.jpbPath = info?.jpbPath;
            dataSource.eventPoint = dataSource.pointId;
            dataSource.drillPersons = "当前参演人员" + (dataSource.personCount) + "位";
            $form._option.dataSource = dataSource;
            $form.render();

            console.log('变更/修改演练', dataSource);

            if ($event === '变更演练') {
                $($editTitle).find('.label-text').text('变更演练');
            } else if ($event === '修改演练') {
                $($editTitle).find('.label-text').text('修改演练');
            }

            // const form = this.getApiPage().retrievePlugin('base-forms');
            // 详情状态
            $form.resetForm('form_19');
            $form.setFormData('form_19', dataSource);
            break;
        case '协同会商':
            config = configs[$event]?.(2);
            // style.width = 650;
            // style.height = 450;
            break;
        default:
            config = configs[$event]?.(2);
        // style.height = 500;
    }

    this.pageObj.getApiWidgetByAliasName('detail-toggle')?.widgetObj.toggle();
    if (config) {
        Modal.type = $event;
        process.renderModal(config, defaultData);
        process?.show(style);
    }
}

